package com.itheima.d6_tcp3;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 实现群聊
 * 当某一个客户端发送过来数据后，就讲该数据转发给其他客户端
 */
public class Server {
    //保存所有客户端的连接Socket
    public static ArrayList<Socket> allClients = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        //线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(80);

        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) { //不断地接收客户端的连接
            Socket socket = serverSocket.accept(); //连接客户端成功
            //保存Socket对象到一个集合中
            allClients.add(socket);
            //将socket封装到群聊任务中，提交给线程池
            threadPool.execute(new QunLiao(socket));
        }

    }
}


/**
 * 接收客户端发送的数据，
 * 并且将数据转发给其他的客户端
 */
class QunLiao implements Runnable {
    private final Socket socket; //服务端接收的客户端对应的Socket对象

    public QunLiao(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        //接收客户端的信息
        try {
            DataInputStream dataInput = new DataInputStream(socket.getInputStream());
            while (true) {
                //读取数据
                String msg = dataInput.readUTF();
                System.out.println(socket.getInetAddress() + " : " +msg);

                //转发数据给其他客户端
                for (Socket client : Server.allClients) {
                    if (client.equals(socket)) {
                        //如果不是自己本身，则转发
                        sendMsg(client,msg);
                    }
                }

                if (msg.equals("886")) {
                    //当前socket结束聊天
                    Server.allClients.remove(socket);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMsg(Socket socket,String msg) throws IOException {
        //发送数据
        DataOutputStream dataOut = new DataOutputStream(socket.getOutputStream());
        dataOut.writeUTF(msg);
    }
}